#!/usr/local/bin/python3
"""
系统排班程序
"""
from datetime import datetime, timedelta
import pymysql
from chinese_calendar import is_workday



class Scheduling_Procedure():
    def __init__(self, dech_start_time):
        self.conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password="123456", db="administration", use_unicode=True, charset='utf8')
        self.cur = self.conn.cursor()
        self.now = datetime.strptime(dech_start_time, '%Y-%m-%d')

    def sql_execute(self, sql):
        """执行 sql 语句"""
        self.cur.execute(sql)
        return self.cur.fetchall()

    def OneRostering(self):
        """一线排班"""
        up_all_data = "UPDATE `personal_center_sortline` SET is_deleted=1"
        self.sql_execute(up_all_data)
        self.conn.commit()

        select_all_sql = "SELECT id FROM personal_center_scheduling WHERE type=1 AND is_work=1"
        select_all_data = self.sql_execute(select_all_sql)
        all_id_list = [i[0] for i in select_all_data]                       # 所有已排过班的ID
        work_number = 0
        while work_number < 7:
            # now = datetime.now()
            # now = datetime.strptime('2022-11-07', '%Y-%m-%d')
            monday = self.now + timedelta(days=work_number)
            print(monday)
            if is_workday(monday):
                print("工作日")
                select_sql = "SELECT * FROM personal_center_scheduling WHERE type=1 AND is_work=0 LIMIT 1"
                sortLine_data = self.sql_execute(select_sql)
                if not sortLine_data:
                    for ids in all_id_list:
                        updata_sql = f"UPDATE personal_center_scheduling SET is_work=0 WHERE id={ids}"
                        self.cur.execute(updata_sql)
                    self.conn.commit()
                    continue

                updata_work_type = f"UPDATE personal_center_scheduling SET day_type='b', is_work='1' WHERE id={sortLine_data[0][0]}"
                self.cur.execute(updata_work_type)
                self.conn.commit()

                insert_sql = f"INSERT INTO personal_center_sortline (type, date, user_id, day_type, is_deleted) VALUES('1', '{str(monday).split(' ')[0]}', '{sortLine_data[0][4]}', 'b', '0')"
                self.cur.execute(insert_sql)
                self.conn.commit()
            else:
                print("休息日")
                select_sql = "SELECT * FROM personal_center_scheduling WHERE type=1 AND is_work=0 LIMIT 2"
                sortLine_data = self.sql_execute(select_sql)
                for t in range(len(sortLine_data)):
                    updata_work_type = f"UPDATE personal_center_scheduling SET is_work='1' WHERE id={sortLine_data[t][0]}"
                    self.cur.execute(updata_work_type)
                self.conn.commit()

                if len(sortLine_data) == 2:
                    insert_sql = f"INSERT INTO personal_center_sortline (type, date, user_id, day_type, is_deleted) VALUES('1', '{str(monday).split(' ')[0]}', '{sortLine_data[0][4]}', 'a', '0')"
                    self.cur.execute(insert_sql)
                    insert_sql = f"INSERT INTO personal_center_sortline (type, date, user_id, day_type, is_deleted) VALUES('1', '{str(monday).split(' ')[0]}', '{sortLine_data[1][4]}', 'b', '0')"
                    self.cur.execute(insert_sql)
                    self.conn.commit()

                elif len(sortLine_data) == 1:
                    insert_sql = f"INSERT INTO personal_center_sortline (type, date, user_id, day_type, is_deleted) VALUES('1', '{str(monday).split(' ')[0]}', '{sortLine_data[0][4]}', 'a', '0')"
                    self.cur.execute(insert_sql)
                    for ids in all_id_list:
                        updata_sql = f"UPDATE personal_center_scheduling SET is_work=0 WHERE id={ids}"
                        self.cur.execute(updata_sql)
                    self.conn.commit()
                    # 取第二位值班人员
                    select_sql = "SELECT * FROM personal_center_scheduling WHERE type=1 AND is_work=0 LIMIT 1"
                    sortLine_data = self.sql_execute(select_sql)

                    updata_work_type = f"UPDATE personal_center_scheduling SET is_work='1' WHERE id={sortLine_data[0][0]}"
                    self.cur.execute(updata_work_type)
                    self.conn.commit()

                    insert_sql = f"INSERT INTO personal_center_sortline (type, date, user_id, day_type, is_deleted) VALUES('1', '{str(monday).split(' ')[0]}', '{sortLine_data[0][4]}', 'b', '0')"
                    self.cur.execute(insert_sql)
                    self.conn.commit()

                else:
                    for ids in all_id_list:
                        updata_sql = f"UPDATE personal_center_scheduling SET is_work=0 WHERE id={ids}"
                        self.cur.execute(updata_sql)
                    self.conn.commit()
                    continue

            work_number += 1

    def TwoRostering(self):
        """二线排班"""
        select_all_sql = "SELECT user_id FROM personal_center_scheduling WHERE type=2 ORDER BY day_type ASC"
        select_all_data = self.sql_execute(select_all_sql)

        two_list = [i[0] for i in select_all_data]
        new_two_list = two_list[2:] + two_list[:2]

        # now = datetime.now()
        # now = datetime.strptime('2022-11-07', '%Y-%m-%d')
        for i in range(7):
            monday = self.now + timedelta(days=i)
            updata_sql = f"UPDATE personal_center_scheduling SET day_type={i+1} WHERE user_id='{new_two_list[i]}'"
            self.sql_execute(updata_sql)
            insert_sql = f"INSERT INTO personal_center_sortline (type, date, user_id, day_type, is_deleted) VALUES('2', '{str(monday).split(' ')[0]}', '{new_two_list[i]}', 'b', '0')"
            self.cur.execute(insert_sql)
        self.conn.commit()


    def main(self):
        self.OneRostering()
        self.TwoRostering()



